package parser

import (
	"clawer/common/engine"
	"regexp"
	"strconv"
	"clawer/common/model"
	"github.com/bitly/go-simplejson"
	"github.com/gpmgo/gopm/modules/log"
)

var (
	ageRe       = regexp.MustCompile(`"age": ([\d]+),`)
	marriageRe  = regexp.MustCompile(`"marriageString": "([\s]+)"`)
	incomeRe    = regexp.MustCompile(`"objectSalaryString": "([\s]+)"`)
	genderRe    = regexp.MustCompile(`"genderString": "([\s]+)"`)
	educationRe = regexp.MustCompile(`"educationString": "([\s]+)"`)
	heightRe    = regexp.MustCompile(`"heightString": "([\s]+)"`)
	detailRe    = regexp.MustCompile(`"detailInfo": \[([\s]+)]`)
	dataRe      = regexp.MustCompile(`<script>window.__INITIAL_STATE__=(.+);\(function`)
)

func ParseProfile(contents []byte, name string) (result engine.ParseResult) {
	profile := model.Profile{}
	jsonData := extractByte(contents, dataRe)
	res, err := simplejson.NewJson(jsonData)
	if err != nil {
		log.Error("ParseProfile NewJson err: %v", err)
		return
	}
	profile.Name = name
	profile.Education = extractString(res, []string{"objectInfo", "educationString"}...)
	profile.Gender = extractString(res, []string{"objectInfo", "genderString"}...)
	profile.Height = extractString(res, []string{"objectInfo", "heightString"}...)
	profile.Income = extractString(res, []string{"objectInfo", "salaryString"}...)
	profile.Residence = extractString(res, []string{"objectInfo", "workProvinceCityString"}...)

	result.Items = []interface{}{profile}
	return result
}

func extractByte(contents []byte, re *regexp.Regexp) []byte {
	match := re.FindSubmatch(contents)
	if len(match) >= 2 {
		return match[1]
	}
	return nil
}

func extractInt(contents []byte, re *regexp.Regexp) int {
	match := re.FindSubmatch(contents)
	if len(match) >= 2 {
		age, err := strconv.Atoi(string(match[1]))
		if err != nil {
			return age
		}
	}
	return 0
}

func extractString(json *simplejson.Json, key ...string) (res string) {
	for _, v := range key {
		json = json.Get(v)
	}
	res, err := json.String()
	if err != nil {
		log.Error("extractString err: %v", err)
	}
	return
}
